package com.ybxx.core.web.servlet;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ybxx.core.util.FileUtil;
/**
 * 功能：文件上传组件类
 * 公司：XA.Co.LTD
 * 制作人：Tom.Y
 * 日期：2011-05*/
public class FileUploadServlet extends HttpServlet{
	private Log logger = LogFactory.getLog(FileUploadServlet.class);

	private ServletConfig servletConfig = null;


	private String uploadPath = "";

	private String tempPath = "";

	private String fileCat = "others";

	private String filePath = "";

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		try{
			DiskFileItemFactory factory = new DiskFileItemFactory();

			factory.setSizeThreshold(4096);
			factory.setRepository(new File(this.tempPath));
			ServletFileUpload fu = new ServletFileUpload(factory);

			List<FileItem> fileItems = fu.parseRequest(req);

			for (FileItem fi : fileItems) {
				if ("file_cat".equals(fi.getFieldName())) {
					this.fileCat = fi.getString();
				}

				if ("file_path".equals(fi.getFieldName())) {
					this.filePath = fi.getString();
				}
			}

			Iterator i = fileItems.iterator();
			StringBuffer sb = new StringBuffer("[");
			while (i.hasNext()){
				FileItem fi = (FileItem)i.next();
				if (fi.getContentType() == null){
					continue;
				}

				String path = fi.getName();
				if(path==null || path.trim().equals("")){
					continue;
				}
				int start = path.lastIndexOf("\\");

				String fileName = path.substring(start + 1);

				String relativeFullPath = null;

				if (!"".equals(this.filePath))
					relativeFullPath = this.filePath;
				else {
					relativeFullPath = this.fileCat + "/" + FileUtil.generateFilename(fileName);
				}

				int index = relativeFullPath.lastIndexOf("/");

				File dirPath = new File(this.uploadPath + "/" + relativeFullPath.substring(0, index + 1));

				if (!dirPath.exists()) {
					dirPath.mkdirs();
				}

				fi.write(new File(this.uploadPath + "/" + relativeFullPath));


				sb.append("{success:true");
				sb.append(",fileName:'").append(fileName).append("',filePath:'").append(relativeFullPath).append("',message:'upload file success.(" + fi.getSize() + " bytes)'");
				sb.append("},");
				
				//缩放
				 String lujing = (new File(this.uploadPath + "/" + relativeFullPath)).toString();

				
			}
			sb=new StringBuffer(sb.substring(0,sb.lastIndexOf(",")));
			sb.append("]");
			System.out.println(sb.toString());
			resp.setContentType("text/html;charset=UTF-8");
			PrintWriter writer = resp.getWriter();
			writer.println(sb.toString());
		}catch (Exception e){
			resp.getWriter().write("{'success':false,'message':'error..." + e.getMessage() + "'}");
		}
	}

	public void init(ServletConfig config) throws ServletException{
		super.init(config);
		this.servletConfig = config;
	}

	public void init()throws ServletException{
		String path = getServletContext().getRealPath("");
		path = path.substring(0,path.lastIndexOf("\\"))+"\\attachFiles\\";
		//this.uploadPath = getServletContext().getRealPath("/attachFiles/");
		
		this.uploadPath = path;
		File uploadPathFile = new File(this.uploadPath);
		if (!uploadPathFile.exists()) {
			uploadPathFile.mkdirs();
		}
		this.tempPath = (this.uploadPath + "/temp");

		File tempPathFile = new File(this.tempPath);
		if (!tempPathFile.exists())
			tempPathFile.mkdirs();
	}

	public boolean saveFileToDisk(String officefileNameDisk){
		File officeFileUpload = null;
		FileItem officeFileItem = null;

		boolean result = true;
		try{
			if ((!"".equalsIgnoreCase(officefileNameDisk)) && (officeFileItem != null)){
				officeFileUpload = new File(this.uploadPath + officefileNameDisk);
				officeFileItem.write(officeFileUpload);
			}
		} catch (FileNotFoundException localFileNotFoundException) {
		}catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		return result;
	}
}
